package br.com.fiap.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.fiap.beans.MenuBean;
import br.com.fiap.beans.filtro.FiltroLogin;
import br.com.fiap.dao.impl.LoginDAOImpl;
import br.com.fiap.entity.Cliente;
import br.com.fiap.entity.Login;
import br.com.fiap.enumeration.TipoUsuario;


/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter({"/cliente/*","/trecho/*","/voo/*","/compraPassagens/*"})
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest)request;
		
		if (req.getSession().getAttribute("usuarioLogado") != null) {
			
			Cliente cliente = (Cliente) req.getSession().getAttribute("usuarioLogado");
			
			MenuBean menuBean = TipoUsuario.populaRoles(TipoUsuario.getEnumByKey(cliente.getTipoUsuario()));
			
			req.getSession().setAttribute("menuBean", menuBean);
			
		}
        	
		FiltroLogin filtroLogin = new FiltroLogin();
		filtroLogin.setLogin(req.getParameter("usuario"));
		
		LoginDAOImpl loginDAO = new LoginDAOImpl();
		Login login;
		
		try {
			
			if(filtroLogin.getLogin() != null){
				login = loginDAO.findByName(filtroLogin.getLogin());
				
				if(!req.getParameter("senha").equals(login.getSenha())){
					req.setAttribute("msgLoginInvalido", "Senha Invalida!");
					FacesContext.getCurrentInstance().getExternalContext().dispatch("cliente/login.xhtml");
				}
					
				req.getSession().setAttribute("usuarioLogado", login.getCliente());

				MenuBean menuBean = TipoUsuario.populaRoles(TipoUsuario.getEnumByKey(login.getCliente().getTipoUsuario()));
				
				req.getSession().setAttribute("menuBean", menuBean);
			}
			chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
